const User = require('../models/user');
const Question = require('../models/question');
const CollectQuestionList = require('../models/collectQuestionList');
const {Op} = require('sequelize');
//用户与收藏列表一对多关系
User.hasMany(CollectQuestionList,{foreignKey:'user_id',sourceKey:'user_id'});
CollectQuestionList.belongsTo(User,{foreignKey:'user_id',targetKey:'user_id'});

//问题与收藏列表一对多关系
Question.hasMany(CollectQuestionList,{foreignKey:'question_id',sourceKey:'question_id'});
CollectQuestionList.belongsTo(Question,{foreignKey:'question_id',targetKey:'question_id'});

class CollectQuestionListsCtl{
  //查看特定用户的收藏列表
  async findByUserId(ctx){
    const { count,rows } = await CollectQuestionList.findAndCountAll({
      where:{
        user_id:ctx.state.user.user_id
      },
      
    })
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  //添加新收藏
  async collectQuestion(ctx){
    const question_id = ctx.params.id;
    const user_id = ctx.state.user.user_id
    const collect = await CollectQuestionList.create({
      user_id,
      question_id
    });
    ctx.body = collect
  }
  //取消收藏
  async uncollectQuestion(ctx){
    const question_id= ctx.params.id;
    const collect = await CollectQuestionList.findOne({
      where:{
        [Op.and]:{
          question_id,
          user_id:ctx.state.user.user_id
        }
      }
    })
    await collect.destroy();
    ctx.status = 204
  }
}

module.exports = new CollectQuestionListsCtl();
